package org.gd.jms.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;

public class RabbitMQGetter implements Runnable {

    private static Integer classCount = 1;
    private Integer number;
    private ConnectionFactory factory;
    private String QUEUE_NAME;
    private boolean isBusy = false;

    public RabbitMQGetter() {
        factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");
        factory.setPort(5672);
    }

    public RabbitMQGetter(String QUEUE_NAME) {
        this();
        number = classCount++;
        this.QUEUE_NAME = QUEUE_NAME;
    }

    @SuppressWarnings("unused")
    public String getQUEUE_NAME() {
        return QUEUE_NAME;
    }

    @SuppressWarnings("unused")
    public boolean isBusy() {
        return isBusy;
    }

    @Override
    public void run() {
        try {
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            QueueingConsumer consumer = new QueueingConsumer(channel);
            channel.basicConsume(QUEUE_NAME, true, consumer);
            while(true) {
                try {
                    QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                    isBusy = true;
                    long timeStart = System.currentTimeMillis();
                    String message = new String(delivery.getBody());
                    Thread.sleep(Math.round(Math.random() * 100));
                    log(timeStart, message);
                    isBusy = false;
                } catch (Throwable e) {
                    e.printStackTrace(System.err);
                    System.exit(0);
                }
            }
        } catch (IOException e) {
            e.printStackTrace(System.err);
            System.exit(0);
        }
    }

    private void log(long timeStart, String message) {



        System.out.println(" [" + this.getClass().getSimpleName() + ":" + number + "] Received '" + message + "'; time: " + (System.currentTimeMillis() - timeStart) + "ms");
    }
}
